package cn.tuling.standard;

import java.util.ArrayList;
import java.util.List;

/**
 * 安全模式： 叶子结点与树枝节点具有不同的接口，客户端需要知道叶子结点和树枝节点 的存在，失去了透明性。
 */
public class SafetyTest {
    public static void main(String[] args) {
        CompositeSafety root = new CompositeSafety();
        CompositeSafety c1 = new CompositeSafety();
        ComponentSafety leaf1 = new LeafSafety("1");
        ComponentSafety leaf2 = new LeafSafety("2");
        ComponentSafety leaf3 = new LeafSafety("3");

        root.add(leaf1);
        root.add(c1);

        c1.add(leaf2);
        c1.add(leaf3);

        root.operate();
    }
}

interface ComponentSafety {
    void operate();
}

class LeafSafety implements ComponentSafety {
    private String name;

    public LeafSafety(String name) {
        this.name = name;
    }

    @Override
    public void operate() {
        System.out.println("叶子" + name + "结点执行操作。");
    }
}

class CompositeSafety implements ComponentSafety {
    private List<ComponentSafety> children = new ArrayList<>();

    public void add(ComponentSafety component) {
        children.add(component);
    }

    public void remove(ComponentSafety component) {
        children.remove(component);
    }

    public ComponentSafety getChild(int i) {
        return children.get(i);
    }

    @Override
    public void operate() {
        for (ComponentSafety child : children) {
            child.operate();
        }
    }
}